import { routerRedux } from 'dva/router'; // 获取路由的参数
import { stringify } from 'qs';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  // 异步处理请求并且合并store值
  effects: {
    // 调用也是 namespace名加此函数名dispatch({type: 'login/logout'});
    // 一共有三个参数，第一个不用可以写_, 后面{回调, put是改变合并store值的}
    *login({ payload }, { call, put }) {
      console.log('请求login层', payload)
      // 同步先回调，传入封装的函数，在就是传入了当前页面接收的值（视情况而定用）
      const response = yield call(fakeAccountLogin, payload); // 网络获取用户角色
      // 把异步请求接收到的值，在触发reducers内的changeLoginStatus函数--派发任务合并store值
      yield put({
        type: 'changeLoginStatus',
        payload: response, // 把异步请求的派发给reducers内处理
      });

      // 登录成功以后更新权限，跳转页面
      if (response.status === 'ok') {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        // 处理路由历史记录，进行替换
        yield put(routerRedux.replace(redirect || '/'));
      }

    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      const { redirect } = getPageQuery();
      // redirect
      if (window.location.pathname !== '/user/login' && !redirect) {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          })
        );
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      console.log('type::', payload.type)
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
